const mysql = require('mysql2');
const util = require("../../common/util");

// 创建连接池，设置连接池的参数
const pool = mysql.createPool({
    host: '127.0.0.1',
    password:"458092",
    user: 'root',
    database: 'schoolwall',
    waitForConnections: true,
    connectionLimit: 10,
    maxIdle: 10, // 最大空闲连接数，默认等于 `connectionLimit`
    idleTimeout: 60000, // 空闲连接超时，以毫秒为单位，默认值为 60000 ms
    queueLimit: 0,
    enableKeepAlive: true,
    keepAliveInitialDelay: 0,
});


/** 
 * 
 * @returns {Promise} 
 */ 
function query(sql, values) {
    return new Promise((resolve, reject) => {
        pool.getConnection((err, connection) => {
            if (err) {
                util.FormatJSONData(300, "请求失败");
                reject(err);
            } else {
                connection.execute(sql, values, (err, result) => {
                    connection.release();
                    if (err) {
                        reject(err);
                    } else {
                        resolve(result);
                    }
                });
            }
        });
    });
}

module.exports = {
    query
}

